package utils;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;

public class FileUtils {
	
	/**
	 * 字符串流转换成字符串
	 * @param is
	 * @return
	 * @throws Exception
	 */
	public static String streamToString(InputStream is) throws Exception {

		BufferedReader in = new BufferedReader(new InputStreamReader(is));
		StringBuffer buffer = new StringBuffer();
		String line = "";
		while ((line = in.readLine()) != null)
			buffer.append(line).append("\n");
		return buffer.toString();
	}

	/**
	 * 将字符串输出到文件
	 * @param outputFile
	 * @param outputText
	 * @throws Exception
	 */
	public static void writeTextToFile(String filePath, String text)throws Exception {
		File outputFile = new File(filePath);
		Writer ow = new OutputStreamWriter(new FileOutputStream(outputFile),
				"UTF-8");
		ow.write(text);
		ow.close();
	}

	/**
	 * 检测目录是否存在，不存在则建立
	 * @param dirPath
	 */
	public static void checkDir(String dirPath) {
		File dir = new File(dirPath);
		if (!dir.exists())
			dir.mkdirs();
	}
	public static void rm(String dirPath) {
		File file = new File(dirPath);
		if (file.exists() && file.isFile())
			file.delete();
	}
	public static void copy(File src, File dst) {

		InputStream in = null;
		OutputStream out = null;
		try {
			in = new BufferedInputStream(new FileInputStream(src), 1024 * 10);
			out = new BufferedOutputStream(new FileOutputStream(dst), 1024 * 10);
			byte[] buffer = new byte[1024 * 10];
			int len = 0;
			while ((len = in.read(buffer)) > 0) {
				out.write(buffer, 0, len);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (null != in) {
				try {
					in.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if (null != out) {
				try {
					out.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}
}
